<?php
	
	$__view;
	$__actions=array();
	$__ajax=false;
	$__is_start_view=false;
	$__manually_viewfile=null;
	$__manually_viewpath=null;
	
	class Controller{
		
		
		
		function Observe($mod_name,$event,$func){
			
		}
		
		function Notify($mod_name,$event){
		
		}
		
		function Post($path,$actionObj,$methods_params){
			
			if($_SERVER["REQUEST_METHOD"]=="POST"){
				global $__actions;
				if($path==null) $path="/";
				foreach((array_keys($methods_params)) as $m){
					if(is_subclass_of($methods_params[$m],"Params") || is_a($methods_params[$m],"Params")){
						$__actions[$path]["methods"][strtolower($m)]=$methods_params[$m]->wrap();
					}else{
						$__actions[$path]["methods"][strtolower($m)]=$methods_params[$m];
					}
                }
				
				$__actions[$path]["object"]=$actionObj;
				
			}
			
		}
		
		function Get($regpath, $file){
			global $__manually_viewfile;
			if($_SERVER["REQUEST_METHOD"]=="GET"){
				//var_dump(getsys("tail_urlpath"));
				//var_dump(preg_match("/{$regpath}/i",getsys("tail_urlpath")));
				if(preg_match("/{$regpath}/i",getsys("tail_urlpath"))){
					
					$__manually_viewfile=pathjoin($viewpath,$file);
				}
			}
		}
		
		function SetView($path){
			global $__manually_viewpath;
			$__manually_viewpath=$path;
			
			//=$path;
		}
		
		function GetViewfile($action=NULL){
			global $__manually_viewpath, $__manually_viewfile;
		
			if(isset($__manually_viewpath)){
				$viewpath=$__manually_viewpath;
			}else{
				$viewpath = $GLOBALS["system"]["view_path"];
			}
			
			if($__manually_viewfile==null){
				
				if($action==NULL){
					
					if(strpos(getsys("tail_urlpath"),"/")===false){
						$action = getsys("tail_urlpath");
						
					}
					
				}
				
				if(!empty($action)){
					$pathname = basename($action);
					$filename =  pathjoin($viewpath,$action.".php");			
				}		 
				if(!file_exists($filename)) {
					$pathname = "index";
					$filename =  pathjoin($viewpath,"index.php");
				}
				
				$files=array();
				if(!file_exists($filename)){
					$dir = dir(dirname($filename));
					if($dir){
						while (false !== ($entry = $dir->read())) {
						   if(is_file(dirname($filename)."/".$entry) && in_array($pathname,explode(",",basename($entry, ".php")))){
								
								$filename =  $viewpath	."/".$entry;
								break;
						   }
						}
						$dir->close();
					}
				}
			}else{
				$filename = pathjoin($viewpath,$__manually_viewfile);
			}
			
			//var_dump($filename);
			return $filename;
		}
		
		
		
		function Run(){
			global $__view,$__actions;
			global $__canRedirect;
			
			$__canRedirect=true;
			
			
			//trigger_error("TEST");
			if($_SERVER["REQUEST_METHOD"]=="GET"){
				$params = new URLParams(":action");
				$GLOBALS["system"]["action"]=$params->action;

				if(class_exists("MainView")){
					$__view = new MainView();
					
					if(method_exists($__view,"onBeforeGet")){
						$content_file=$__view->onBeforeGet();
					}
					header("Content-Type: text/html; charset=utf-8");
					global $__is_start_view;
					$__is_start_view=true;
					if(file_exists($content_file)){
						echo $__view->render($content_file);
					}else{
						
						echo $__view->render(Controller::GetViewfile());
					}
					$__is_start_view=false;
					return;
				}
			}
			
			
			if($_SERVER["REQUEST_METHOD"]=="POST"){
				
			   /*$paths = explode("/",$_SERVER["PATH_INFO"]);
               $actionname = strtolower($paths[count($paths)-1]);
               $actionpaths = array_slice($paths,1,count($paths)-2);
				

               if(empty($_SERVER["PATH_INFO"]) || count($actionpaths)==0) {
                   $action=$__actions["/"];
               }else{
                   $action = $__actions["/".implode("/",$actionpaths)];
               }*/
				//$params = new URLParams(":action");
				//$actionname = $params->action;
				preg_match("/.*\/(.*)$/i",$_SERVER['REDIRECT_URL'],$match);
				$actionname = strtolower($match[1]);
				$GLOBALS["system"]["action"]=$actionname;
				
				$action=$__actions["/"];
				
				
               if(!isset($action["object"])) trigger_error("no action");
				
				  
				
				//if(empty($action->__params))$action->setParams($_POST);
				
				
				global $__ajax;
				$__ajax=true;
				
				$__canRedirect=($_SERVER["HTTP_X_REQUESTED_WITH"]!="XMLHttpRequest");
				
				//if($action->isExposed($actionname)){
				
			   if(count($action["methods"])>0){
			   		
				   if(in_array($actionname,array_keys($action["methods"]))){
						
						if(is_string($action["object"])){
							$ao = mod($action["object"]);
							
						}elseif(is_a($action["object"],"DelegateClass") || is_a($action["object"],"DelegateFunc")){
							$d = $action["object"]; 
							$ao= $d->invoke();
							
						}else{
							$ao= $action["object"];
						}
						
					   $result = call_user_method_array($actionname,$ao,$action["methods"][$actionname]);
					   
						
				   }else{
					   $result=null;
					  
				   }
			   }
				
				if($_SERVER["HTTP_X_REQUESTED_WITH"]=="XMLHttpRequest"){
					header("X-JSON: ".json_encode($result));
					return;

				}

				$__canRedirect=true;
				
				/*if(empty($_SERVER['PATH_INFO'])){
					$afterMethod="after_index";
				}else{
					$afterMethod="after".str_replace("/","_",$_SERVER['PATH_INFO']);
				}*/
				
				if(class_exists("MainView")){
					$__view = new MainView();
					

					$is_postview=true;
					if(method_exists($__view,$afterMethod))  {
						$content_file = $__view->$afterMethod($result);
						$is_postview=true;
					}elseif(method_exists($__view,"onAfterPost")){
						$content_file = $__view->onAfterPost($result);
						$is_postview=true;
					}
						
					if($is_postview){
						header("Content-Type: text/html; charset=utf-8");
						global $__is_start_view;
						$__is_start_view=true;
						if(file_exists($content_file)){
							echo $__view->render($content_file);
						}else{
							$__view->result = $result;
							echo $__view->render(Controller::GetViewfile());
							
						}
						$__is_start_view=false;
						return;
					}
					
				}
				
				//redirect($_SERVER["HTTP_REFERER"]);
				return;
			}
			

		}
		
	
	}
	
?>